<template>
	<view>

		<!-- <u-navbar :is-back="true" title="选择城市" title-color="#000" back-icon-color="#000"></u-navbar> -->
		<u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
			<u-navbar :border-bottom="false" :is-fixed="false" custom-class="home-bg" :is-back="true">
				<view class="nav-top">
					<view class="logo-top">
						<u-search v-model="keyword" placeholder="输入城市名查询" bg-color="#F4F4F4" name="search" size="34"
							@search="onSearch"></u-search>
					</view>
				</view>
			</u-navbar>
		</u-sticky>
		<view class="city-content">
			<view class="content-box">
				<view class="content-left">
					<view class="city-name"
						:class="[index == selectDefalutNum ? 'acitvieColor' : '', 'provicesIndex' + index]"
						v-for="(item,index) in provices" :key="index" :ref="'provicesIndex' + index">
						<text @click="changeCity(item, index)"
							:class="{'acitiveTxt':item.checked==true}">{{item.name}}</text>
					</view>
				</view>
				<view class="content-right" :style="{marginTop: topheight + 'rpx'}">
					<!-- <u-checkbox v-model="isAllcheck" @change="selectall" ><text :class="{'acitvieColor':isAllcheck==true}">全选</text> </u-checkbox> -->
					<!-- <u-checkbox-group @change="checkboxGroupChange">
						
						<u-checkbox @change="checkboxChange($event,item,index)" v-model="item.checked"
							v-for="(item, index) in provices[selectDefalutNum].districts" :key="index"
							:name="item.name"><text :class="{'acitvieColor':item.checked==true}">{{item.name}}</text></u-checkbox>
					</u-checkbox-group> -->
					<template v-if="selectPrivice === '推荐'">
						<view class="city-tips city-tips-light mb20">
							选择您所在的城市，可以看到更多附近机构和内容~
						</view>
						<view class="city-tips mb20 city-tips-ot">
							<text>最近访问</text>
						</view>
						<view class="city-item-container">
							<view class="city-item-main" v-for="(item, index) in hisCity" :key="index">
								<text class="city-item line1" :class="{'acitvieColor':item.checked==true}"
									@click="selectCityTj(item)">{{item.name}}</text>
								<text class="city-icon-colse" size="10" @click.stop="closeHis(index)">×</text>
							</view>
						</view>

						<view class="city-tips mb20">
							热门城市
						</view>
						<view class="city-item-container">
							<text class="city-item line1" :class="{'acitvieColor':item.checked==true}"
								v-for="(item, index) in hotCity" :key="index"
								@click="selectCityTj(item)">{{item.name}}</text>
						</view>
					</template>


					<view class="city-item-container">
						<text v-if="selectPrivice !== '推荐'" class="city-item line1"
							:class="{'acitvieColor':item.checked==true}"
							v-for="(item, index) in provices[selectDefalutNum].districts" :key="index"
							@click="selectCity(item)">{{item.name}}</text>
					</view>

				</view>
			</view>
		</view>
	</view>

</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import PageExposure from "@/mixins/page_exposure.js"
	let provices = require('./provice.json')
	const app = getApp();

	export default {
		mixins: [PageExposure],
		data() {
			return {
				isAllcheck: false,
				cityList: [],
				selectVal: [],
				height: 1000,
				provices: provices,
				selectDefalutNum: 0, //默认选择第一个
				navBarHeight: app.globalData.navBarHeight,
				menuHeight: app.globalData.menuHeight,
				menuBotton: app.globalData.menuBotton,
				menuTop: app.globalData.menuTop,
				selectPrivice: provices[0].name,
				hisCity: [],
				keyword: '',
				hotCity: [{
						name: '北京城区',
						parent: '北京市'
					},
					{
						name: '成都市',
						parent: '四川省'
					},
					{
						name: '上海城区',
						parent: '上海市'
					},
					{
						name: '广州市',
						parent: '广东省'
					},
					{
						name: '深圳市',
						parent: '广东省'
					},
					{
						name: '杭州市',
						parent: '浙江省'
					},
					{
						name: '重庆城',
						parent: '重庆市'
					},
					{
						name: '南京市',
						parent: '江苏省'
					}
				],
				colseCityState: false,
				jumpPage: '/pages/index/index',
				topheight: null
			}
		},
		watch: {},
		computed: {
			...mapGetters(["appConfig"]),
			navBackground() {
				return this.seting.top_bg_image ? {
					'background-image': `url(${this.seting.top_bg_image})`
				} : {}
			},
			seting() {
				const {
					index_setting
				} = this.appConfig
				return index_setting
			}
		},
		methods: {
			closeHis(index) {
				this.hisCity.splice(index, 1)
				const that = this
				wx.setStorage({
					key: 'city',
					data: JSON.stringify(that.hisCity),
					success(res) {
						console.log('保存历史记录成功', res)
					}
				})
			},
			doClose() {
				this.openClose = true
			},
			doOpen() {
				this.openClose = false
			},
			onSearch() {
				this.provices.forEach((item, index) => {
					// if (item.name.includes(this.keyword)) {
					// 	this.selectDefalutNum = index
					// 	this.changeCity(item, index)
					// }
					if (item.districts && item.districts.length) {
						item.districts.forEach((_item, _index) => {
							if (_item.name.includes(this.keyword)) {
								this.selectDefalutNum = index
								this.changeCity(item, index)
							}
						})
					}
				})
			},
			selectall(e) {
				/*同步问题 去反*/
				if (!this.isAllcheck) {

					//表示全选
					this.provices[this.selectDefalutNum].checked = true
					this.provices[this.selectDefalutNum].districts.map((item) => {
						return item.checked = true
					})


				} else {

					this.provices[this.selectDefalutNum].checked = false
					//表示全不选
					this.provices[this.selectDefalutNum].districts.map((item) => {
						return item.checked = false
					})
				}
				this.getAllselectVal()
			},
			changeCity(item, num) {
				if (item.name == '全部城市') {
					this.selectCity({
						selectPrivice: '全部城市',
						name: '全部城市'
					});
					return;
				}
				this.selectPrivice = item.name
				this.isAllcheck = false
				this.selectDefalutNum = num
				for (let item of this.provices[this.selectDefalutNum].districts) {

					if (!item.checked) {
						item.checked = false
					}
					if (!item.disabled) {
						item.disabled = false
					}

				}

				const query = uni.createSelectorQuery()
				query
					.select('.provicesIndex' + num)
					.boundingClientRect((data) => {
						let pageScrollTop = Math.round(data.top - this.topheight)
						uni.pageScrollTo({
							scrollTop: pageScrollTop, //滚动的距离
							duration: 500, //过渡时间
						})
					})
					.exec()

				/*判断一下是否被选择*/
				this.checkSelectType()
			},
			selectCity(item) {
				getApp().globalData.privice = this.selectPrivice
				getApp().globalData.city = item.name
				let stepState = true
				this.hisCity.forEach(_item => {
					if (_item.name === item.name) {
						stepState = false
					}
				})
				if (stepState) {
					this.hisCity.push({
						name: item.name,
						parent: this.selectPrivice
					})
					const that = this
					wx.setStorage({
						key: 'city',
						data: JSON.stringify(that.hisCity),
						success(res) {
							console.log('保存历史记录成功', res)
						}
					})
				}

				uni.switchTab({
					url: this.jumpPage
				});
			},
			selectCityTj(item) {
				getApp().globalData.privice = item.parent
				getApp().globalData.city = item.name
				let stepState = true
				this.hisCity.forEach(_item => {
					if (_item.name === item.name) {
						stepState = false
					}
				})
				if (stepState) {
					this.hisCity.push({
						name: item.name,
						parent: item.parent
					})
					const that = this
					wx.setStorage({
						key: 'city',
						data: JSON.stringify(that.hisCity),
						success(res) {
							console.log('保存历史记录成功', res)
						}
					})
				}

				uni.switchTab({
					url: this.jumpPage
				});
			},
			// 选中某个复选框时，由checkbox时触发
			checkboxChange(e, val, num) {
				this.$set(this.provices[this.selectDefalutNum].districts, num, val)

			},
			// 选中任一checkbox时，由checkbox-group触发
			checkboxGroupChange(e) {

				//当数组勾选全部时 全选选中
				this.checkSelectType()
				this.getAllselectVal()

			},
			checkSelectType() {


				if (this.provices[this.selectDefalutNum].districts.length == 0) {
					this.provices[this.selectDefalutNum].checked = false
					this.$set(this.provices, this.selectDefalutNum, this.provices[this.selectDefalutNum])
					this.isAllcheck = false
					return
				} else {

					let data = this.provices[this.selectDefalutNum].districts.filter((item) => {
						if (item.checked) {
							return item
						}
					})


					if (data.length == this.provices[this.selectDefalutNum].districts.length) {

						this.provices[this.selectDefalutNum].checked = true
						this.$set(this.provices, this.selectDefalutNum, this.provices[this.selectDefalutNum])
						this.isAllcheck = true
					} else if (data.length > 0) {

						this.provices[this.selectDefalutNum].checked = true
						this.$set(this.provices, this.selectDefalutNum, this.provices[this.selectDefalutNum])
					} else {

						this.provices[this.selectDefalutNum].checked = false
						this.$set(this.provices, this.selectDefalutNum, this.provices[this.selectDefalutNum])
						this.isAllcheck = false
					}

				}


			},
			//获取所有选中的值
			getAllselectVal() {
				let provicedata;
				let sendprovicedata = [];
				let citydata = [];
				provicedata = this.provices.filter(item => {
					if (item.checked) {
						let {
							districts,
							...params
						} = item
						sendprovicedata.push(params)
						return item

					}
				})
				for (let items of provicedata) {
					items.districts.filter(item => {
						if (item.checked) {
							//去除掉三级 
							let {
								districts,
								...params
							} = item
							citydata.push(params)
						}
					})
				}
				//传递数据给搜索页
				let datas = {
					"provice": sendprovicedata,
					"city": citydata
				}

				this.$store.commit('ADD_SELECTCITY', JSON.stringify(datas))
				uni.setStorageSync('ADD_SELECTCITY', JSON.stringify(datas))


			},
			dealData(data) {
				if (data.provice.length > 0 || data.city.length > 0) {

					for (let item of this.provices) {
						for (let m of data.provice) {
							if (item.areaCode == m.areaCode) {
								item.checked = m.checked
								for (let k of item.districts) {
									for (let v of data.city) {
										if (v.areaCode == k.areaCode) {
											k.checked = v.checked
										}
									}
								}
							}
						}
					}
				}
			},
			defalutData() {
				for (let item of this.provices[this.selectDefalutNum].districts) {
					item.checked = false
					item.disabled = false
				}
			},
			getTopHeight() {
				let that = this;
				uni.getSystemInfo({
					success: function(e) {
						//48为自定义导航栏高度，一般为44
						let topPx = e.statusBarHeight + 48 // 顶部状态栏+沉浸式自定义顶部导航
						that.topheight = topPx / (uni.upx2px(topPx) / topPx) // px转rpx，这里必须转化为rpx，不然适配失败
					},
				});
			}
		},

		onLoad(query) {
			// let that = this;
			// // 获取系统信息
			// wx.getSystemInfo({
			// 	success: function(res) {
			// 		// 获取可使用窗口宽度
			// 		let clientHeight = res.windowHeight;
			// 		// 设置高度
			// 		that.setData({
			// 			height: clientHeight - (that.navBarHeight + 8)
			// 		});
			// 	}
			// })
			const that = this
			wx.getStorage({
				key: 'city',
				success(res) {
					console.log(res, 'res')
					if (!res.data) {
						that.hisCity = []
					} else {
						that.hisCity = JSON.parse(res.data)
					}
				},
				fail() {
					that.hisCity = []
				}
			})

			if (query.page == 'institution') {
				this.jumpPage = '/pages/institution/institution'
			}
		},
		created() {
			/*获取stroe数据  回显*/
			for (let val of this.provices) {
				val.checked = false
			}
			if (uni.getStorageSync("ADD_SELECTCITY")) {
				this.dealData(JSON.parse(uni.getStorageSync("ADD_SELECTCITY")))
				//检查默认的是否全选了
				this.checkSelectType()
			} else {
				this.defalutData()
			}
			this.getTopHeight();
		},
		mounted() {}
	}
</script>

<style scoped>
	.city-content {
		width: 100%;
		background: white;
		overflow: hidden;


	}

	.content-box {
		width: 100%;
		/* height: 100vh; */
		overflow: hidden;
		display: flex;
		justify-content: space-between;
		position: relative;

	}

	.content-left {

		width: 280rpx;
		/* height: 100vh; */
		background: #F2F2F2;
		overflow-y: scroll;
	}

	.content-right {
		width: 470rpx;
		/* height: 100vh; */
		overflow-y: scroll;
		box-sizing: border-box;
		padding: 20rpx;
		position: fixed;
		top: 0;
		right: 0;
	}

	.city-item {
		width: 31%;
		padding: 0 16rpx;
		height: 60rpx;
		background-color: rgb(245, 245, 245);
		line-height: 60rpx;
		text-align: center;
		margin-right: 20rpx;
		margin-bottom: 16rpx;
		display: inline-block;
		margin-right: 3.5%;
		font-size: 24rpx;
	}

	.city-item-container .city-item:nth-child(3n) {
		margin-right: 0;
	}

	.city-item-main {
		position: relative;
		width: 31%;
		margin-right: 3.5%;
		display: inline-block;
	}

	.city-item-main .city-item {
		width: 100%;
	}

	.city-item-container .city-item-main:nth-child(3n) {
		margin-right: 0;
	}

	.city-icon-colse {
		position: absolute;
		right: -8rpx;
		display: flex;
		line-height: 10rpx;
		align-items: center;
		justify-content: center;
		top: -8rpx;
		width: 20rpx;
		height: 20rpx;
		border-radius: 10rpx;
		border: 2rpx solid #0B67F1;
		color: #0B67F1;
		background-color: #ffffff;
	}

	.city-name {
		width: 100%;
		text-align: center;
		height: 96rpx;
		line-height: 96rpx;
		color: #595959;
		font-size: 24rpx;
	}

	.city-name text {
		display: block;
		width: 100%;
		height: 100%;
		text-align: center;
	}

	.acitvieColor {
		background: white;
		color: #0B67F1;
	}

	.acitvieColor text {
		color: #0B67F1;
	}

	.acitiveTxt {
		color: #0B67F1;
	}

	.city-name-select text {
		width: auto;
	}

	.city-name-select {
		display: flex;
		justify-content: space-around;
	}

	/deep/ .u-checkbox {
		display: inline-block !important;
		width: 100% !important;
		height: 96rpx;
		line-height: 96rpx;
		justify-content: space-evenly;

	}

	/deep/.u-checkbox__label {
		float: left;
		height: 96rpx;
		line-height: 96rpx;
		margin-left: 40rpx !important;
	}

	/deep/.u-checkbox__icon-wrap {
		float: right;
		height: 96rpx;
		line-height: 96rpx;
		margin-right: 30rpx;
		margin-top: 31rpx;
	}

	.city-tips {
		font-size: 24rpx;
		opacity: 0.8;
	}

	.city-tips-ot {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.city-tips-light {
		color: #9E9E9E;
	}
</style>